package com.bite;


class TreeNode {
 int val = 0;
 TreeNode left = null;
 TreeNode right = null;

 public TreeNode(int val) {
 this.val = val;

 }

 }

public class Solution {
    public TreeNode Convert(TreeNode pRootOfTree) {
        if(pRootOfTree == null){
            return null;
        }
        if(pRootOfTree.left == null && pRootOfTree.right == null){
            return pRootOfTree;
        }


        if(pRootOfTree.left != null && pRootOfTree.right != null){
            TreeNode ret = TreeToLink(pRootOfTree.left);
            TreeNode leftLast = pRootOfTree.left;
            while(leftLast.left != null){
                leftLast = leftLast.left;
            }
            TreeNode rightSmall = TreeToLink(pRootOfTree.right);
            leftLast.right = pRootOfTree;
            pRootOfTree.left = leftLast;
            rightSmall.left = pRootOfTree;
            pRootOfTree.right = rightSmall;
            return ret;

        }else if(pRootOfTree.left != null){
            TreeNode ret = TreeToLink(pRootOfTree.left);
            TreeNode leftLast = pRootOfTree.left;
            while(leftLast.left != null){
                leftLast = leftLast.left;
            }
            leftLast.right = pRootOfTree;
            pRootOfTree.left = leftLast;
            return ret;
        }else{
            TreeNode ret = TreeToLink(pRootOfTree.right);
            ret.left = pRootOfTree;
            pRootOfTree.right = ret;
            return ret;
        }
    }

    public TreeNode TreeToLink(TreeNode parent){
        if(parent == null)return null;
        TreeNode leftTree = TreeToLink(parent.left);
        TreeNode rightTree = TreeToLink(parent.right);
        if(leftTree != null){
            leftTree.right = parent;
            parent.left = leftTree;
        }
        if(rightTree != null){
            rightTree.left = parent;
            parent.right = rightTree;
        }
        if(leftTree != null && rightTree != null){
            return leftTree;
        }else if(rightTree != null){
            return rightTree;
        }else{
            return parent;
        }

    }
}
